var sys = require("sys");
var http = require("http");
var paperboy = require("paperboy");

var todo = {
    todoList: require("./todo-list"),
    todoListController: require("./todo-list-controller")
}

module.exports = {
    create: function (router) {
        var server = Object.create(this);
        server.todoList = Object.create(todo.todoList);
        server.http = http.createServer(server.request.bind(server));
        server.router = router;

        return server;
    },

    request: function (req, res) {
        var route = this.router.match(req.method, req.url);

        if (route) {
            this.loadController(route.params.controller)[route.params.action](req, res);
        } else {
            paperboy.deliver("public", req, res).otherwise(function () {
                res.writeHead(404, { "Content-Type": "text/html" });
                res.write("<h1>Nothing to see here, move along</h1>");
                res.end();
            });
        }
    },

    listen: function () {
        return this.http.listen.apply(this.http, arguments);
    },

    loadController: function (name) {
        var controller = Object.create(todo[name]);
        controller.list = this.todoList;

        return controller;
    }
};
